package cn.sunxiansheng.intelligent.analysis.consumer;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import cn.sunxiansheng.intelligent.analysis.entity.ELKEntity;
import cn.sunxiansheng.intelligent.analysis.utils.MailUtil;
import com.vladsch.flexmark.html.HtmlRenderer;
import com.vladsch.flexmark.parser.Parser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;

/**
 * Description: 死信队列监听
 *
 * @Author sun
 * @Create 2025/1/2 12:39
 * @Version 1.0
 */
@Component
@Slf4j
public class DlxQueueListener {

    @Resource
    private MailUtil mailUtil;

    private static final String to = "sunxiansehng@gmail.com";

    /**
     * 死信队列消息消费方法
     *
     * @param message 死信队列中的消息
     */
    @RabbitListener(queues = "dlxQueue")
    public void receiveDlxMessage(Message message) {
        // 处理死信消息，通常是日志记录、报警或人工干预
        log.error("DlxQueueListener：接收到死信消息");
        // 获取消息体
        String messageBody = new String(message.getBody(), StandardCharsets.UTF_8);
        // 使用 Jackson 将消息体反序列化为 ELKEntity 对象
        ObjectMapper objectMapper = new ObjectMapper();
        // 忽略掉未知属性
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

        try {
            ELKEntity elkEntity = objectMapper.readValue(messageBody, ELKEntity.class);
            String logger = elkEntity.getLogger();
            String throwable = elkEntity.getThrowable();
            String module = elkEntity.getModule();
            String timestamp = elkEntity.getTimestamp();
            String host = elkEntity.getHost();
            String logMessage = elkEntity.getLogMessage();
            sendMailWithDetails("线上报错（死信队列消息）", "无", timestamp, logger, module, host, logMessage, throwable);
        } catch (Exception e) {
            log.error("DlxQueueListene：反序列化消息失败", e);
        }
    }

    private void sendMailWithDetails(String subject, String analysisResult, String timestamp, String logger,
                                     String module, String host, String logMessage, String throwable) throws Exception {
        // 构建邮件的HTML格式内容
        String htmlContent = buildHtmlContent(subject, analysisResult, timestamp, logger, module, host, logMessage, throwable);

        // 发送邮件
        mailUtil.sendHtmlMessage(to, "SunRays-Framework", subject, htmlContent);
    }

    public String buildHtmlContent(String subject, String analysisResult, String timestamp, String logger,
                                   String module, String host, String logMessage, String throwable) {
        // 使用 Flexmark 将 analysisResult 转换为 HTML
        Parser parser = Parser.builder().build();
        HtmlRenderer renderer = HtmlRenderer.builder().build();
        String analysisHtml = renderer.render(parser.parse(analysisResult));

        // 构建 HTML 内容
        return "<html><body>" +
                "<h2>" + subject + "</h2>" +
                "<table border='1' cellpadding='10' cellspacing='0'>" +
                "<tr><td><strong>时间戳</strong></td><td>" + timestamp + "</td></tr>" +
                "<tr><td><strong>日志器</strong></td><td>" + logger + "</td></tr>" +
                "<tr><td><strong>模块</strong></td><td>" + module + "</td></tr>" +
                "<tr><td><strong>主机</strong></td><td>" + host + "</td></tr>" +
                "<tr><td><strong>日志信息</strong></td><td>" + logMessage + "</td></tr>" +
                "<tr><td><strong>异常信息</strong></td><td><pre>" + throwable + "</pre></td></tr>" +
                "</table>" +
                "<h3>AI分析结果：</h3>" +
                "<div>" + analysisHtml + "</div>" +  // 渲染后的分析结果
                "</body></html>";
    }
}